import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:socket_io_client/socket_io_client.dart' as SocketIO;
import 'package:socket_io_client/socket_io_client.dart';

class StreamSocket<T> {
  final _socketResponse = StreamController<T>();

  Stream<T> get getResponse => _socketResponse.stream;

  final String host;
  final int port;
  late final Socket _socket;
  final String recvEvent;
  final String userId;

  StreamSocket(
      {required this.host,
      required this.port,
      required this.recvEvent,
      required this.userId}) {
    _socket = SocketIO.io('ws://$host:$port', <String, dynamic>{
      'transports': ['websocket'],
      'autoConnect': true,
      'forceNew': true
    });
  }

  void connectAndListen() {
    _socket.onConnect((_) {
      debugPrint('connected');
      regsiter();
    });

    _socket.onReconnect((data) {
      debugPrint('Reconnected');
      regsiter();
    });

    _socket.onConnectTimeout((data) => debugPrint('timeout'));
    _socket.onConnectError((error) => debugPrint(error.toString()));
    _socket.onError((error) => debugPrint(error.toString()));
    _socket.on(recvEvent, (data) {
      _socketResponse.sink.add(data);
    });
    _socket.onDisconnect((_) => debugPrint('disconnect'));
  }

  void regsiter() {
    _socket.emit('register', userId);
  }

  void unregsiter() {
    _socket.emit('unregister', userId);
  }

  void sendMessage(String event, T message) {
    _socket.emit(event, message);
    _socketResponse.sink.add(message);
  }

  void close() {
    _socketResponse.close();
    _socket.disconnect().close();
  }
}

class MessageModel with ChangeNotifier {
  String _message = '';
  String get message => _message;
  set message(value) => _message = value;
}
